package com.example.himalaya.presenters;

import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.example.himalaya.model.api.OnDemandDataApi;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.IPlayerViewCallback;
import com.example.himalaya.presenters.interfaces.IPlayerPresenter;
import com.example.himalaya.utils.LogUtil;
import com.ximalaya.ting.android.opensdk.datatrasfer.IDataCallBack;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.track.TrackList;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.constants.PlayerConstants;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PlayerPresenter implements IPlayerPresenter, IXmAdsStatusListener, IXmPlayerStatusListener {

    // Constent

    private static final String TAG = "PlayerPresenter";


    //PLAY_MODEL_SINGLE     单曲播放
    //PLAY_MODEL_SINGLE_LOOP 单曲循环播放
    //PLAY_MODEL_LIST       列表播放
    //PLAY_MODEL_LIST_LOOP  列表循环
    //PLAY_MODEL_RANDOM     随机播放

    public static final int PLAY_MODEL_RANDOM_INT = 0;
    public static final int PLAY_MODEL_SINGLE_LOOP_INT = 1;
    public static final int PLAY_MODEL_LIST_INT = 2;
    public static final int PLAY_MODEL_LIST_LOOP_INT = 3;

    public static final int DEFAULT_PLAY_INDEX = 0;


    public static final String PLAY_MODE_SP_NAME = "PlayMod";
    public static final String PLAY_MODE_SP_KEY = "currentPlayMode";


    // List
    private List<IPlayerViewCallback> mPlayerCallbacks = new ArrayList<>();


    // Logic object
    private XmPlayerManager mPlayerManager;

    // Variable

    private Track mCurrentTrack;
    private int mCurrentIndex = 0;
    private final SharedPreferences mPlayModSp;

    private XmPlayListControl.PlayMode mCurrentPlayMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST;


    // Flag
    private boolean mIsReverse = false;

    private PlayerPresenter() {
        mPlayerManager = XmPlayerManager.getInstance(BaseApplication.getAppContext());

        // 广告相关的接口
        mPlayerManager.addAdsStatusListener(this);

        // 注册播放器状态相关的接口
        mPlayerManager.addPlayerStatusListener(this);


        // 需要记录当前的播放模式
        mPlayModSp = BaseApplication.getAppContext().getSharedPreferences(PLAY_MODE_SP_NAME, Context.MODE_PRIVATE);
    }

    private static PlayerPresenter sPlayerPresenter;


    public static PlayerPresenter getPlayerPresenter() {
        if (sPlayerPresenter == null) {
            synchronized (PlayerPresenter.class) {
                if (sPlayerPresenter == null) {
                    sPlayerPresenter = new PlayerPresenter();
                }
            }

        }

        return sPlayerPresenter;
    }

    public void setPlayList(List<Track> list, int playIndex) {
        if (mPlayerManager != null) {
            mPlayerManager.setPlayList(list, playIndex);
            mCurrentTrack = list.get(playIndex);

            mCurrentIndex = playIndex;
        } else {
            LogUtil.d(TAG, "mPlayerManager is null");
        }

    }


    @Override
    public void play() {
        if (mPlayerManager != null) {
            int playerStatus = mPlayerManager.getPlayerStatus();

            LogUtil.d(TAG, "Play -> PlayerStatus->" + playerStatus);

            mPlayerManager.play();
        }
    }

    @Override
    public void pause() {
        if (mPlayerManager != null) {
            mPlayerManager.pause();
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public void playPre() {
        if (mPlayerManager != null) {
            mPlayerManager.playPre();
        }
    }

    @Override
    public void playNext() {
        if (mPlayerManager != null) {
            mPlayerManager.playNext();
        }
    }

    @Override
    public void switchPlayMode(XmPlayListControl.PlayMode mode) {
        if (mPlayerManager != null) {

            // 记录当前播放模式到全局变量
            mCurrentPlayMode = mode;

            mPlayerManager.setPlayMode(mode);

            // 通知UI更新播放模式
            for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
                iPlayerViewCallback.onPlayModeChange(mode);
            }

            // 保存到sp里面去
            SharedPreferences.Editor editor = mPlayModSp.edit();

            editor.putInt(PLAY_MODE_SP_KEY, getIntByPlayMode(mode));

            editor.apply();
        }
    }

    private int getIntByPlayMode(XmPlayListControl.PlayMode mode) {

        switch (mode) {
            case PLAY_MODEL_LIST_LOOP:
                return PLAY_MODEL_LIST_LOOP_INT;
            case PLAY_MODEL_LIST:
                return PLAY_MODEL_LIST_INT;
            case PLAY_MODEL_RANDOM:
                return PLAY_MODEL_RANDOM_INT;
            case PLAY_MODEL_SINGLE_LOOP:
                return PLAY_MODEL_SINGLE_LOOP_INT;
            default:
                LogUtil.d(TAG, "Something logic wrong");
                break;
        }

        return PLAY_MODEL_LIST_INT;
    }

    private XmPlayListControl.PlayMode getPlayModeByInt(int index) {

        switch (index) {
            case PLAY_MODEL_LIST_LOOP_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
            case PLAY_MODEL_LIST_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
            case PLAY_MODEL_RANDOM_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM;
            case PLAY_MODEL_SINGLE_LOOP_INT:
                return XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP;
            default:
                LogUtil.d(TAG, "Something logic wrong");
                break;
        }
        return XmPlayListControl.PlayMode.PLAY_MODEL_LIST;

    }

    @Override
    public void getPlayList() {

        if (mPlayerManager != null) {
            List<Track> playList = mPlayerManager.getPlayList();
            for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
                iPlayerViewCallback.onListLoaded(playList);
            }
        }
    }

    @Override
    public void playByIndex(int index) {
        // 切换播放器到第index的位置进行播放
        mPlayerManager.play(index);
    }

    @Override
    public void seekTo(int progress) {
        // 更新播放器的进度
        mPlayerManager.seekTo(progress);
    }

    @Override
    public boolean isPlaying() {
        return mPlayerManager.isPlaying();
    }

    /**
     * 把播放列表反转
     */
    @Override
    public void reversePlayList() {
        List<Track> playList = mPlayerManager.getPlayList();
        Collections.reverse(playList);

        mIsReverse = !mIsReverse;

        // 第一个参数是播放列表, 第二个是开始播放的下标
        mCurrentIndex = playList.size() - 1 - mCurrentIndex;
        mPlayerManager.setPlayList(playList, mCurrentIndex);

        // 跟新UI
        mCurrentTrack = (Track) mPlayerManager.getCurrSound();
        for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
            iPlayerViewCallback.onListLoaded(playList);
            iPlayerViewCallback.onTrackUpdate(mCurrentTrack, mCurrentIndex);
            iPlayerViewCallback.updateListOrder(mIsReverse);
        }


    }

    @Override
    public void playByAlblumId(long id) {
        // 1. 要获取专辑的列表内容
        OnDemandDataApi searchApi = OnDemandDataApi.getOnDemandDataApi();

        searchApi.getTracks((int) id, 1, 1, new IDataCallBack<TrackList>() {
            @Override
            public void onSuccess(TrackList trackList) {
                // 2. 把专辑内容设置给播放器
                List<Track> tracks = trackList.getTracks();

                if (trackList != null && tracks.size() > 0) {
                    mPlayerManager.setPlayList(tracks, DEFAULT_PLAY_INDEX);

                    // 修改Flag and Tool
                    mCurrentIndex = DEFAULT_PLAY_INDEX;
                    mCurrentTrack = tracks.get(DEFAULT_PLAY_INDEX);
                }
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                LogUtil.d(TAG, "errorCode -->" + errorCode);
                LogUtil.d(TAG, "errorMsg -->" + errorMsg);
                Toast.makeText(BaseApplication.getAppContext(), "请求数据错误。。", Toast.LENGTH_LONG).show();
            }

        });
        // 3. 播放。。。
    }

    @Override
    public void registerViewCallback(IPlayerViewCallback iPlayerViewCallback) {

        if (mPlayerCallbacks != null) {
            mPlayerCallbacks.add(iPlayerViewCallback);
        }

        // 更新之前， 让UI的Pager
        getPlayList();
        // 通知当前的节目
        iPlayerViewCallback.onTrackUpdate(mCurrentTrack, mCurrentIndex);

        // 从sp里面拿到保存的当前播放模式
        int modeIndex = mPlayModSp.getInt(PLAY_MODE_SP_KEY, PLAY_MODEL_LIST_INT);

        mCurrentPlayMode = getPlayModeByInt(modeIndex);

        // 将保存的播放模式通知UI层显示
        iPlayerViewCallback.onPlayModeChange(mCurrentPlayMode);

        // 读取底层状态再次改变UI 通知UI层显示

        if (mPlayerManager.isPlaying()) {
            iPlayerViewCallback.onPlayStart();
        }

        // iPlayerViewCallback.onPlayStart();

    }

    @Override
    public void unRegisterViewCallback(IPlayerViewCallback iPlayerViewCallback) {

    }

    //==================== 广告相关的回调 START=============

    @Override
    public void onStartGetAdsInfo() {
        LogUtil.d(TAG, "onStartGetAdsInfo...");
    }

    @Override
    public void onGetAdsInfo(AdvertisList advertisList) {
        LogUtil.d(TAG, "onGetAdsInfo");

    }

    @Override
    public void onAdsStartBuffering() {
        LogUtil.d(TAG, "onAdsStartBuffering");

    }

    @Override
    public void onAdsStopBuffering() {
        LogUtil.d(TAG, "onAdsStopBuffering");

    }

    @Override
    public void onStartPlayAds(Advertis advertis, int i) {
        LogUtil.d(TAG, "onStartPlayAds");

    }

    @Override
    public void onCompletePlayAds() {
        LogUtil.d(TAG, "onCompletePlayAds");

    }

    @Override
    public void onError(int what, int extra) {
        LogUtil.d(TAG, "onError what -- >" + what + "extra -->" + extra);
    }
    //==================== 广告相关的回调 END=============


    // ================ 播放器相关的回调 START=========
    @Override
    public void onPlayStart() {
        LogUtil.d(TAG, "onPlayStart");
        for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
            iPlayerViewCallback.onPlayStart();
        }
    }

    @Override
    public void onPlayPause() {
        LogUtil.d(TAG, "onPlayPause");
        for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
            iPlayerViewCallback.onPlayPause();
        }
    }

    @Override
    public void onPlayStop() {
        LogUtil.d(TAG, "onPlayStop");
        for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
            iPlayerViewCallback.onPlayStop();
        }
    }

    @Override
    public void onSoundPlayComplete() {
        LogUtil.d(TAG, "onSoundPlayComplete");

    }

    @Override
    public void onSoundPrepared() {
        LogUtil.d(TAG, "onSoundPrepared");

        // 播放之前设置用户选择的播放模式
        mPlayerManager.setPlayMode(mCurrentPlayMode);

        if (mPlayerManager.getPlayerStatus() == PlayerConstants.STATE_PREPARED) {
            // 播放器准备完了， 可以去播放了
            mPlayerManager.play();
        }
    }

    @Override
    public void onSoundSwitch(PlayableModel lastModel, PlayableModel curModel) {
        LogUtil.d(TAG, "onSoundSwitch");
        if (lastModel != null) {
            LogUtil.d(TAG, "lastModel -->" + lastModel.getKind());
        }
        LogUtil.d(TAG, "curModel -->" + curModel.getKind());

        // curModel 代表的是当前播放的内容
        // 如果通过getKind()方法得到他的类型为tarck

        //if("track".equals(curModel.getKind())) {
        //    Track currentTrack = (Track) curModel;
        //    LogUtil.d(TAG, "title -->" + currentTrack.getTrackTitle());
        //}

        // 第二种写法
        mCurrentIndex = mPlayerManager.getCurrentIndex();

        if (curModel instanceof Track) {

            mCurrentTrack = (Track) curModel;

            LogUtil.d(TAG, "title -->" + mCurrentTrack.getTrackTitle());

            // 保存播放记录
            HistoryPresenter historyPresenter = HistoryPresenter.getInstance();
            historyPresenter.addHistory(mCurrentTrack);

            for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
                iPlayerViewCallback.onTrackUpdate(mCurrentTrack, mCurrentIndex);
            }

        }

    }

    @Override
    public void onBufferingStart() {
        LogUtil.d(TAG, "onBufferingStart ...");

    }

    @Override
    public void onBufferingStop() {
        LogUtil.d(TAG, "onBufferingStop ...");

    }

    @Override
    public void onBufferProgress(int i) {
        LogUtil.d(TAG, "onBufferProgress ->" + i);

    }

    @Override
    public void onPlayProgress(int currPos, int duration) {
        // 进度条 单位是毫秒
//        LogUtil.d(TAG, "onPlayProgress" + currPos + "duration" + duration);
        for (IPlayerViewCallback iPlayerViewCallback : mPlayerCallbacks) {
            iPlayerViewCallback.onProgressChange(currPos, duration);
        }
    }

    @Override
    public boolean onError(XmPlayerException e) {
        LogUtil.d(TAG, "onError e --->" + e);

        return false;
    }

    /**
     * 判断是否有播放列表
     *
     * @return true 为空  false 为有数据
     */
    public boolean hasPlayList() {
        List<Track> playList = mPlayerManager.getPlayList();
        return playList != null && playList.size() > 0;
    }
    // ================ 播放器相关的回调 END=========
}
